package com.sk.bilibili.utils;

import android.util.Log;

import androidx.annotation.NonNull;

import com.sk.bilibili.dto.Res;
import com.sk.bilibili.callBack.RequestCallBack;
import com.sk.bilibili.other.BiliBiliException;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RequestUtils {

    /**
     * Rxjava内存泄漏问题
     */
    public static <T> void process(Observable<Res<T>> observable, RequestCallBack<T> callBack){
        observable.subscribeOn(Schedulers.io())//保证耗时操作在非UI线程  返回数据在UI线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Res<T>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        callBack.start();
                    }
                    @Override
                    public void onNext(@NonNull Res<T> res) {
                        if(res.getCode()==200){
                            callBack.success(res.getData());
                        }else {
                            callBack.error(new BiliBiliException(res.getMsg()));
                        }
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        callBack.error(e);
                    }
                    @Override
                    public void onComplete() {
                        callBack.end();
                    }
                });
    }

    // 用于处理不关心结果的请求
    public static <T> void process(Observable<Res<T>> observable) {
        process(observable, new RequestCallBack<T>() {
            @Override
            public void success(T t) {
                Log.e("BILIBILI","请求成功");
            }
            @Override
            public void error(Throwable throwable) {
                Log.e("BILIBILI","请求失败"+throwable.toString());
            }
        });
    }

}